#include "timerManager.h"

Timer::Timer(int32_t repeat)
:m_period(0)
,m_repeat(repeat) 
,m_func(nullptr)
{
    m_time = Now();
}
 
Timer::~Timer()
{
    
}


void Timer::OnTimer()
{
    if(!m_func || m_repeat == 0)
    {
        return;
    }

    m_func();
    m_time += m_period;
    if(m_repeat > 0)
    {
        --m_repeat;
    }
}

//返回当前时间戳
uint64_t Timer::Now()
{
    //获取当前时间戳
    auto now = std::chrono::system_clock::now();

    //将当前时间戳转换成毫秒数
    auto now_ms = std::chrono::time_point_cast<std::chrono::microseconds>(now);
    
    return now_ms.time_since_epoch().count();
}

//================================================================================

//管理定时任务
void TimerManager::UpDate()
{
    if(m_timers.empty())
    {
        return;
    }

    uint64_t now = Timer::Now();
    for(auto it = m_timers.begin(); it != m_timers.end();)
    {
        if(it->first > now)
        {
            return;
        }

        it->second.OnTimer();

        Timer t = it ->second;
        it = m_timers.erase(it); //同时更新迭代器

        if(t.GetRepeat() != 0)
        {
            auto newIt = m_timers.insert(std::make_pair(t.GetTime(), t));
            //如果newIt是当前唯一的任务 或者 newIt的触发时间早于it
            if(it == m_timers.end() || newIt->first < it->first)
            {
                it = newIt;
            }
        }
    }
}